package com.wyz.easyexcel.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Locale;
import java.util.Optional;
import com.wyz.easyexcel.constant.RequestConstant;

/**
 * @author wyz
 * @description: 请求工具类
 * @date 2021/12/30 17:15
 */
@Slf4j
public class RequestUtil {

    private RequestUtil(){}

    /**
     *  获取 HttpServletRequest 对象
     * @return
     */
    public static HttpServletRequest getRequest(){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = Optional.ofNullable(requestAttributes).map(ServletRequestAttributes::getRequest)
                .orElseThrow(()-> new NullPointerException("该次请求线程中，获取HttpServletRequest对象时，为null"));
        return request;
    }



    /**
     *  获取浏览器请求所在地区
     * @return
     */
    public static Locale getLocal(){
        return getRequest().getLocale();
    }


    /**
     *  获取请求头中自定义的locale 如果没有则获取浏览器请求所在地区的locale
     * @return
     */
    public static Locale getLanguageOrRequest(){
        Locale language = getLanguage();

        return  Optional.of(language).orElse(getLocal());
    }

    /**
     *  获取请求头中的自定义的locale
     * @return
     */
    public static Locale getLanguage(){
        String language = getRequestHeaderParam(RequestConstant.REQUEST_HEADER_LANGUAGE);
        Optional<Locale> first = Arrays.stream(Locale.getAvailableLocales()).filter(locale ->
                locale.toString().equalsIgnoreCase(language)).findFirst();
        return first.orElse(null);
    }


    /**
     * 获取请求body中参数
     * @param key
     * @return
     */
    public static String getRequestParam(String key) {
        return getRequest().getParameter(key);
    }


    /**
     * 获取请求头参数
     * @param key
     * @return
     */
    public static String getRequestHeaderParam(String key) {
        return getRequest().getHeader(key);
    }


}


